package com.atguigu.common.utils;

import com.atguigu.common.cron.bean.FrontPageBean;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * @Author panghl
 * @Date 2021/3/12 10:34
 * @Description Map  与  Object 相互转换
 **/
public class MapObjectUtil {

    //Object转Map
    public static Map<String, Object> getObjectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            if (value == null) {
                value = "";
            }
            map.put(fieldName, value);
        }
        return map;
    }

    //Map转Object
    public static Object getMapToObject(Map<Object, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        Object obj = beanClass.newInstance();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            if (map.containsKey(field.getName())) {
                field.set(obj, map.get(field.getName()));
            }
        }
        return obj;
    }

    public static void main(String[] args) {
        FrontPageBean frontPageBean = new FrontPageBean();
        Map<Object,Object> map = new HashMap<>();
        List<Object> list = new ArrayList<>();
        list.add("test");
        map.put("records",list);
        map.put("current",1);
        map.put("pages",1);
        map.put("size",1);
        map.put("total",1);
        map.put("hasNext",true);
        map.put("hasPrevious",true);
        try {
            FrontPageBean mapToObject = (FrontPageBean)getMapToObject(map, FrontPageBean.class);
            System.out.println(mapToObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
